from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

'''
Those models are not useful on their own, but are used by all other models
'''

class TypeCachedManager(models.Manager):
    '''
    Manager that caches results.
    We should switch to django-orm-cache one day
    '''
    _cache = {}
    
    def lazy_get(self, name):
        if name in self._cache:
            return self._cache[name]
        self._cache[name] = self.get(name=name)
        return self._cache[name]


class Type(models.Model):
    '''
    Abstract taxonomy model that stores types of models
    '''
    name = models.CharField(max_length=50)
    parent = models.ForeignKey('self', null=True, default=None, blank=True)
    cached = TypeCachedManager()
    objects = models.Manager()

    class Meta:
        abstract = True
        app_label = 'openpolitics'

    def __unicode__(self):
        return self.name

class TimeRelation(models.Model):
    '''
    Basic model for Many2Many relations that adds time intervals to the picture
    '''
    date_start = models.DateField(null=True, blank=True)
    date_end = models.DateField(null=True, blank=True)

    class Meta:
        abstract = True
        app_label = 'openpolitics'

class DataType(Type):
    '''
    Taxonomy model that describes types of data items
    '''
    class Meta:
        app_label = 'openpolitics'

class DataItem(models.Model):
    '''
    Single pieces of data in a form of key-value pair that can be
    attached to other models
    '''
    type = models.ForeignKey(DataType)
    value = models.CharField(max_length=150)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()

    class Meta:
        app_label = 'openpolitics'

    def __unicode__(self):
        return '%s: %s (%s)' % (self.type.name, self.value, self.content_object)
